<template>
  <view class="form-container">
    <uni-forms ref="form" :model="formData" :rules="rules">
      <!-- 商品名称 -->
      <uni-forms-item label="商品名称" required name="name">
        <uni-easyinput v-model="formData.name" placeholder="请输入商品名称" />
      </uni-forms-item>
      
      <!-- 价格输入 -->
      <uni-forms-item label="价格(元)" required name="price">
        <uni-easyinput 
          type="digit"
          v-model="priceYuan"
          placeholder="请输入价格"
          @input="updatePrice"
        />
      </uni-forms-item>
      
      <!-- 分类选择 -->
      <uni-forms-item label="分类" required name="category">
        <uni-data-select 
          v-model="formData.category"
          :localdata="categories"
        />
      </uni-forms-item>
      
      <!-- 材质选择 -->
      <uni-forms-item label="材质" required name="material">
        <uni-data-select 
          v-model="formData.material"
          :localdata="materials"
        />
      </uni-forms-item>
      
      <!-- 封面图 -->
      <uni-forms-item label="封面图" required name="cover">
        <uni-file-picker 
          v-model="coverFiles"
          fileMediatype="image"
          limit="1"
          @success="uploadSuccess"
        />
        <!-- 显示已上传的封面图 -->
        <image v-if="formData.cover" :src="formData.cover" class="cover-preview" mode="aspectFit" />
      </uni-forms-item>
      
      <!-- 商品描述 -->
      <uni-forms-item label="商品描述" name="description">
        <uni-easyinput 
          type="textarea"
          v-model="formData.description" 
          placeholder="请输入商品详细描述"
          class="description-textarea"
        />
      </uni-forms-item>
      
      <!-- 上架状态 -->
      <uni-forms-item label="上架状态">
        <switch :checked="formData.status" @change="(e) => formData.status = e.detail.value" />
      </uni-forms-item>
      
      <!-- 提交按钮 -->
      <button type="primary" @click="submit" class="submit-btn">添加商品</button>
    </uni-forms>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [
        { value: '沙发', text: '沙发' },
        { value: '餐桌椅', text: '餐桌椅' },
        { value: '床具', text: '床具' },
        { value: '柜架', text: '柜架' },
        { value: '茶几', text: '茶几' },
        { value: '办公家具', text: '办公家具' }
      ],
      materials: [
        { value: '紫檀', text: '紫檀' },
        { value: '黄花梨', text: '黄花梨' },
        { value: '红酸枝', text: '红酸枝' },
        { value: '鸡翅木', text: '鸡翅木' },
        { value: '乌木', text: '乌木' }
      ],
      formData: {
        name: '',
        price: null, // 以分为单位
        category: '',
        material: '',
        cover: '',
        description: '',
        status: true  // 默认上架
      },
      priceYuan: '',   // 前端显示的价格（元）
      coverFiles: [],   // uni-file-picker需要数组格式
      
      // 表单验证规则
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '请输入商品名称'
          }]
        },
        price: {
          rules: [{
            required: true,
            errorMessage: '请输入价格'
          }, {
            format: 'number',
            errorMessage: '价格必须是数字'
          }]
        },
        category: {
          rules: [{
            required: true,
            errorMessage: '请选择分类'
          }]
        },
        material: {
          rules: [{
            required: true,
            errorMessage: '请选择材质'
          }]
        },
        cover: {
          rules: [{
            required: true,
            errorMessage: '请上传封面图'
          }]
        }
      }
    }
  },
  methods: {
    // 更新价格（元转分）
    updatePrice(value) {
      this.formData.price = value ? Math.round(parseFloat(value) * 100) : null;
    },
    
    // 图片上传成功处理
    uploadSuccess(e) {
      console.log('上传成功:', e);
      if (e.tempFilePaths && e.tempFilePaths.length > 0) {
        this.formData.cover = e.tempFilePaths[0];
      }
    },
    
    async submit() {
      try {
        // 表单验证
        const validate = await this.$refs.form.validate();
        if (validate) {
          // 添加用户ID
          const userInfo = uni.getStorageSync('userInfo');
          if (userInfo && userInfo._id) {
            this.formData.user_id = userInfo._id;
          }
          
          // 保存数据
          const db = uniCloud.database();
          const res = await db.collection('furniture').add(this.formData);
          
          if (res.result && res.result.id) {
            uni.showToast({ 
              title: '添加成功',
              icon: 'success'
            });
            
            // 延迟返回
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            throw new Error('添加失败，请重试');
          }
        }
      } catch (e) {
        console.error('添加失败:', e);
        uni.showToast({ 
          title: e.message || '添加商品失败', 
          icon: 'none' 
        });
      }
    }
  }
}
</script>

<style scoped>
.form-container {
  padding: 30rpx;
  background-color: #f8f3ed;
}

.description-textarea {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: white;
}

.cover-preview {
  width: 200rpx;
  height: 200rpx;
  margin-top: 20rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e8c39e;
}

.submit-btn {
  margin-top: 40rpx;
  background-color: #5c3c1c;
  color: white;
  border-radius: 8rpx;
  height: 80rpx;
  line-height: 80rpx;
}
</style>